<template>
  <el-dialog
    v-model="dialogVisible"
    title="自定义AI角色"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      @submit.prevent
    >
      <el-form-item label="角色名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入角色名称，如：专业翻译助手"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="角色描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="2"
          placeholder="请简要描述这个角色的特点和用途"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="角色分类" prop="category">
        <el-select v-model="formData.category" placeholder="选择角色分类">
          <el-option
            v-for="category in ROLE_CATEGORIES"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          >
            <span> {{ category.name }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="角色头像" prop="avatar">
        <div class="avatar-selector">
          <el-input
            v-model="formData.avatar"
            placeholder="输入emoji或留空使用默认"
            style="width: 200px"
            maxlength="2"
          />
          <div class="avatar-preview">
            {{ formData.avatar || '🤖' }}
          </div>
        </div>
      </el-form-item>

      <el-form-item label="系统提示" prop="prompt">
        <el-input
          v-model="formData.prompt"
          type="textarea"
          :rows="6"
          placeholder="请输入详细的角色设定和行为指导，这将影响AI的回答风格和专业程度..."
          maxlength="1000"
          show-word-limit
        />
        <div class="prompt-tips">
          <el-text size="small" type="info">
            💡 提示：详细的角色设定能让AI更好地理解您的需求。可以包括：性格特征、专业背景、回答风格等。
          </el-text>
        </div>
      </el-form-item>
    </el-form>

    <!-- 预览区域 -->
    <div class="role-preview">
      <el-divider>角色预览</el-divider>
      <div class="preview-content">
        <div class="preview-header">
          <span class="preview-avatar">{{ formData.avatar || '🤖' }}</span>
          <div class="preview-info">
            <div class="preview-name">{{ formData.name || '未命名角色' }}</div>
            <div class="preview-desc">{{ formData.description || '暂无描述' }}</div>
          </div>
        </div>
        <div class="preview-prompt">
          <el-text size="small" type="info">系统提示词预览：</el-text>
          <div class="prompt-content">
            {{ formData.prompt || '暂无提示词' }}
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          创建角色
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useAIChatStore } from '@/stores/aiChatStore'
import { ROLE_CATEGORIES, type RoleFormData } from '@/types/aiRole'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'role-created', role: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const aiChatStore = useAIChatStore()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)

const formData = reactive<RoleFormData>({
  name: '',
  description: '',
  prompt: '',
  category: 'general',
  avatar: ''
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { min: 5, max: 100, message: '角色描述长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择角色分类', trigger: 'change' }
  ],
  prompt: [
    { required: true, message: '请输入系统提示词', trigger: 'blur' },
    { min: 10, max: 1000, message: '提示词长度在 10 到 1000 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 方法
const handleClose = () => {
  // 重置表单
  formRef.value?.resetFields()
  Object.assign(formData, {
    name: '',
    description: '',
    prompt: '',
    category: 'general',
    avatar: ''
  })
  emit('update:modelValue', false)
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 创建角色
    const newRole = aiChatStore.addCustomRole({
      name: formData.name,
      description: formData.description,
      prompt: formData.prompt,
      category: formData.category,
      avatar: formData.avatar
    })

    emit('role-created', newRole)
    handleClose()
    
  } catch (error) {
    console.error('Form validation failed:', error)
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.avatar-selector {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar-preview {
  font-size: 24px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  background: var(--el-bg-color-page);
}

.prompt-tips {
  margin-top: 8px;
}

.role-preview {
  margin-top: 20px;
}

.preview-content {
  background: var(--el-bg-color-page);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  padding: 16px;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.preview-avatar {
  font-size: 24px;
}

.preview-info {
  flex: 1;
}

.preview-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.preview-desc {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.preview-prompt {
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 12px;
}

.prompt-content {
  margin-top: 8px;
  padding: 8px;
  background: var(--el-fill-color-lighter);
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.5;
  color: var(--el-text-color-regular);
  max-height: 100px;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 深色模式适配 */
html.dark .avatar-preview {
  background: var(--el-bg-color);
  border-color: var(--el-border-color-dark);
}

html.dark .preview-content {
  background: var(--el-bg-color);
  border-color: var(--el-border-color-dark);
}

html.dark .prompt-content {
  background: var(--el-fill-color-dark);
}
</style>
